package com.mvu.banana.user.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.http.client.UrlBuilder;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;
import com.mvu.banana.common.client.CommonConstants;
import com.mvu.banana.common.client.GlobalResources;
import com.mvu.banana.common.client.SystemConstants;
import com.mvu.banana.domain.client.MyConstants;
import com.mvu.banana.guest.client.Guest;
import com.mvu.banana.guest.client.ProfilePage;
import com.mvu.banana.internal.client.Admin;

public class User implements EntryPoint, SystemConstants, ValueChangeHandler<String>, KeyUpHandler {

  public void onModuleLoad() {
    GlobalResources.get.css().ensureInjected();
    CommonConstants.registerConstants(MyConstants.get);
    /*    Dictionary dictionary = Dictionary.getDictionary(PAGE_DICTIONARY);
    String auth = dictionary.get("auth");
    if(auth != null && auth.equals("true"))*/
    RootPanel.get().addDomHandler(this, KeyUpEvent.getType());
    // history change
    History.addValueChangeHandler(this);
    // process hash
    String hash = Window.Location.getHash();
    int page = 0;
    if (hash != null && !hash.isEmpty()) {
      page = Integer.valueOf(hash.substring(1));
    }
    loadPage(page);
  }

  private void loadPage(final int page) {
    if (page == Tiles.class.getName().hashCode()) {
      new Tiles().go();
    } else if (page == ProfilePage.class.getName().hashCode()) {
      new ProfilePage().go();
    } else if (page == Admin.class.getName().hashCode()) {
      new Admin().go();
    } else {
      new Guest().go();
    }
  }

  @Override
  public void onValueChange(ValueChangeEvent<String> event) {
    String value = event.getValue();
    if (value != null && !value.isEmpty()) {
      Integer page = Integer.valueOf(value);
      loadPage(page);
    }
  }

  @Override
  public void onKeyUp(KeyUpEvent event) {
    if (event.isAltKeyDown() && event.isShiftKeyDown()
            && event.getNativeKeyCode() == 80 /* p */) {
      UrlBuilder urlBuilder = Window.Location.createUrlBuilder()
              .setHash(String.valueOf(Admin.class.getName().hashCode()));
      Window.open(urlBuilder.buildString(), "", "resizable=1,width=800,height=600");
    }
  }
}
